package com.example.covid19.service.impl;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.covid19.FaceUtil.FaceMe;
import com.example.covid19.common.Dto.RegisterDto;
import com.example.covid19.common.lang.Result;
import com.example.covid19.entity.User;
import com.example.covid19.entity.UserDiscount;
import com.example.covid19.entity.UserRole;
import com.example.covid19.mapper.UserMapper;
import com.example.covid19.service.UserDiscountService;
import com.example.covid19.service.UserRoleService;
import com.example.covid19.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.covid19.util.SecretUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.util.*;

import static com.example.covid19.util.SecretUtil.secret;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author BaiZhengChun
 * @since 2022-09-12
 */
@Slf4j
@Service
@SaCheckLogin
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    FaceMe faceMe;
    private final UserDiscountService userDiscountService;
    private final UserRoleService userRoleService;

    public UserServiceImpl(UserDiscountService userDiscountService, UserRoleService userRoleService) {
        this.userDiscountService = userDiscountService;
        this.userRoleService = userRoleService;
    }

    @Override
    public Result doLogin(String studentid, String password) {
        User user = this.getOne(new QueryWrapper<User>().eq(
                "studentid", Integer.valueOf(studentid)
        ));
        if (user == null) {
            return Result.fail(401, "用户不存在", null);
        }

        boolean flag = user.getPassword().equals(
                SecureUtil.hmacSha1(secret)
                        .digestHex(password)
        );
        if (flag) {
            StpUtil.login(user.getUserid());
            System.out.println(StpUtil.getTokenValue());
            Map<String, Object> objectMap = new HashMap<>(2);
            objectMap.put("token", StpUtil.getTokenInfo());
            user.setPassword(null);
            objectMap.put("user", user);
            return Result.success(200, "登陆成功", objectMap);
        } else {
            return Result.fail(400, "密码错误", null);
        }
    }

    @Override
    public Result register(RegisterDto registerDto) throws Exception {
        String code = registerDto.getCode();
        String c = stringRedisTemplate.opsForValue().get(registerDto.getPhone());
        System.out.println(stringRedisTemplate.opsForValue().get(registerDto.getPhone()));
        System.out.println(code);
        boolean codeFlag = code.equals(c);
        if (!codeFlag) {
            return Result.fail(406, "验证码不正确", null);
        }
        String secret = SecretUtil.secret;
        User user = new User();
        user.setStudentid(registerDto.getStudentid());
        user.setUsername(registerDto.getUsername());
        user.setFacetoken(registerDto.getFacetoken());
        user.setPassword(SecureUtil.hmacSha1(secret).digestHex(registerDto.getPassword()));
        user.setPhone(registerDto.getPhone());
//        user.setRole("学生");
        String uuid = UUID.randomUUID().toString();
        user.setUsrid(uuid);
        UserRole userRole = new UserRole();
        userRole.setUsrid(uuid);
        userRole.setRoleid(2);

        User users = this.getOne(new QueryWrapper<User>().eq("studentid",registerDto.getStudentid()));
        if (users != null) {
            return Result.fail(406, "用户已经存在", null);
        }
        boolean flag = this.save(user);
        if (!flag) {
            return Result.fail(406, "用户创建失败", null);
        }
        UserDiscount discount = new UserDiscount();
        discount.setStudentid(registerDto.getStudentid());
        discount.setDiscount(1);
        boolean dFlag = userDiscountService.save(discount);
        faceMe.faceadd(registerDto.getFacetoken());
        System.out.println(user.getStudentid());
        userRoleService.save(userRole);
        return dFlag ? Result.success(200,"注册成功",null) : Result.fail(406, "用户创建失败", null);

    }
    @Override
    public void sendMessage(String phone) {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential("AKID73mGVVFk00kFVVFl24qMcdOt9AvQggRw", "HJ5buxlJbdV8WeW9WdU6SYOzKQHvLVv6");
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {phone};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId("1400527069");
            req.setSignName("辽东学院");
            req.setTemplateId("972395");
            String code = RandomStringUtils.randomNumeric(6);
            System.out.println(code);
            // 验证码，附加文字，但是不能超过12个字符
            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);
            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            long codeTimeout = 300;
//            redisUtils.setValue(phone, code, codeTimeout);
            stringRedisTemplate.opsForValue().set(phone, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
    }
    @Override
    public Result Facelogin(MultipartFile multipartFile) throws Exception {
        String facetoken = faceMe.face2(multipartFile);
        List<String> list = faceMe.sea(facetoken);
        int confidence = (int) Double.parseDouble(list.get(0));
        String token = list.get(1);
        boolean flag = true;
        if (confidence >= 80) {
            return Facel(token);
        }
        return Result.fail(403, "登陆失败", null);
    }
    public Result Facel(String token) {
        User user = this.getOne(new QueryWrapper<User>().eq(
                "facetoken", token
        ));
//        stringRedisTemplate.opsForValue().set("hello", "Hello World");
        if (user == null) {
            return Result.fail(401, "用户不存在", null);
        }
        if (user.getDeid()==1){
            return Result.fail(400,"该用户已被注销",null);
        }

        StpUtil.login(user.getUserid());
        System.out.println(StpUtil.getTokenValue());
        Map<String, Object> objectMap = new HashMap<>(2);
        objectMap.put("token", StpUtil.getTokenInfo());
        user.setPassword(null);
        objectMap.put("user", user);
        return Result.success(200, "登陆成功", objectMap);

    }
    @Override
    public Result upsave(JSONArray jsonArray){
        List<UserRole> userRoleList = new ArrayList<>();
        List<User> userList = JSONUtil.toList(jsonArray, User.class);
        boolean flag =  this.saveBatch(userList);
        for (User u:
                userList) {
            UserRole userRole = new UserRole();
            userRole.setRoleid(2);
            userRole.setUsrid(u.getUsrid());
            userRoleList.add(userRole);
        }
        userRoleService.saveBatch(userRoleList);
        if (flag){
            return Result.success(200,"成功",null);
        }else {
            return Result.fail(400,"失败",null);
        }
    }
}
